from django.http import HttpResponse
from django.shortcuts import render

from Many2Many.models import User, Movie


# Create Many2Many views here.


# 增加用户数据
def add_user(request):
    for i in range(1, 10):
        User.objects.create(name=f'小{i}子', age=10+i)

    return HttpResponse('添加用户成功！')


# 增加电影数据
def add_movie(request):
    for i in range(1, 10):
        Movie.objects.create(name=f'异形{i}', duration=100+i)
    return HttpResponse('添加电影成功！')


# 添加收藏
def add_collection(request):

    # /many2many/add_collection/?user_id=1&movie_id=1
    user_id = request.GET.get('user_id')
    movie_id = request.GET.get('movie_id')

    # 让user收藏movie
    user = User.objects.get(id=user_id)
    movie = Movie.objects.get(id=movie_id)
    user.movies.add(movie)  # 添加收藏

    return HttpResponse('添加收藏成功！')


# 删除收藏
def delete_collection(request):
    user_id = request.GET.get('user_id')
    movie_id = request.GET.get('movie_id')

    # 删除User表中数据和Movie表中数据都不会互相影响
    # 删除User
    # User.objects.get(id=user_id).delete()
    # 删除Movie
    # Movie.objects.get(id=movie_id).delete()

    # 删除中间表数据，也就是删除收藏
    # 思路有两种
    # 第一种：找到某个人的所有电影，然后删除收藏的指定电影
    user = User.objects.get(id=user_id)
    # user.movies.filter(id=movie_id).delete()   # delete()会真的删掉这个电影数据
    movie = Movie.objects.get(id=movie_id)
    user.movies.remove(movie)   # remove()可以保证值删掉中间表中存放的收藏关系，不删除电影

    return HttpResponse('删除收藏成功！')


# 查询数据
def get_user_movie(request):
    # 获取用户收藏的所有电影
    user = User.objects.get(id=1)
    print(user.movies.all())

    # 获取收藏该电影的所有用户
    movie = Movie.objects.get(id=1)
    print(movie.user_set.all())

    return HttpResponse('查找成功！')
